package com.rdxer.core.security;

import com.rdxer.core.ex.StringEx;
import com.rdxer.model.Account;
import lombok.Getter;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;

@ToString
@Getter
public class AppUserDetails implements UserDetails {

    public AppUserDetails(Account account) {
        this.account = account;

        roles = account.getRoles().split(",");

        Collection<SimpleGrantedAuthority> asList = new ArrayList<>();
        for (String role : roles) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role);
            asList.add(authority);
        }

        authorities = asList;
    }

    public static AppUserDetails getCurrent() {
        return (AppUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    private Collection<? extends GrantedAuthority> authorities;
    public Account account;
    public String[] roles;

    public AppUserDetails(Account account, Collection<? extends GrantedAuthority> authorities) {
        this.account = account;
        this.authorities = authorities;
    }

    public Account getAccount() {
        return account;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return account.getPassword();
    }

    @Override
    public String getUsername() {
        return account.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return account.getDisabledDate() == null;
    }


    public boolean isAdmin() {
        for (String role : this.roles) {
            if (Account.Role.admin.name().equals(role)) {
                return true;
            }
        }
        return false;
    }


    public boolean isTeacher() {
        for (String role : this.roles) {
            if (Account.Role.teacher.name().equals(role)) {
                return true;
            }
        }
        return false;
    }

    public boolean isStuden() {
        for (String role : this.roles) {
            if (Account.Role.studen.name().equals(role)) {
                return true;
            }
        }
        return false;
    }
}
